<?php
namespace app\shop\model;

use think\Db;

class ClientDocumentary extends \ShopModel
{
    protected $table = 'sh_client_documentary';

    public function ClientDocumentaryDb(){
        return Db::name('client_documentary');
    }

    //新增跟单
    public function add($params){

        $utid = \request()->header('userId');
        $staff = Db::name('crm_staff')->alias('a')
        ->join('sh_crm_department b','a.department_id = b.department_id')
        ->where('a.staff_id',$utid)->field('a.staff_id,a.staff_name,b.department_name')->find();

        $goods = !empty($params['goods']) ? $params['goods'] : [];
        unset($params['goods']);

        $time = date("Y-m-d H:i:s");

        $params['images'] = !empty($params['images']) ? implode(',',$params['images']) : null;
        $params['create_staff_id'] = $staff['staff_id'];
        $params['create_staff'] = $staff['staff_name'];
        $params['update_staff'] = $staff['staff_name'];
        $params['department'] = $staff['department_name'];
        $params['stage_time'] = $time;
        $params['create_at'] = $time;
        $params['update_at'] = $time;
        
        $id = $this->insertGetId($params);

        //关联产品
        foreach($goods as $goods){
            $tmp = [
                'documentary_id' => $id,
                'goods_id' => $goods
            ];
            Db::name('documentary_goods_relevance')->insert($tmp);
        }

        return true;

    }

    //修改跟单
    public function edit($params){

        $utid = \request()->header('userId');
        $staff = Db::name('crm_staff')->where('staff_id',$utid)->value('staff_name');

        unset($params['client']);
        unset($params['staff']);
        unset($params['stage']);
        unset($params['ago']);

        $params['images'] = !empty($params['images']) ? implode(',',$params['images']) : null;
        $params['update_staff'] = $staff;
        $params['update_at'] = date("Y-m-d H:i:s");

        $goods = !empty($params['goods']) ? $params['goods'] : [];
        unset($params['goods']);

        $old_stage = Db::name('client_documentary')->where('documentary_id',$params['documentary_id'])->value('stage_id');

        if($old_stage != $params['stage_id']){
            $params['stage_time'] = date("Y-m-d H:i:s");
        }

        Db::name('client_documentary')->where('documentary_id',$params['documentary_id'])->update($params);

        //关联产品
        Db::name('documentary_goods_relevance')->where('documentary_id',$params['documentary_id'])->delete();
        foreach($goods as $goods){
            $tmp = [
                'documentary_id' => $params['documentary_id'],
                'goods_id' => $goods
            ];
            Db::name('documentary_goods_relevance')->insert($tmp);
        }


        return true;

    }

    //删除跟单
    public function del_documentary($id){

        //删除主数据
        Db::name('client_documentary')->where('documentary_id',$id)->delete();

        //删除关联产品
        Db::name('documentary_goods_relevance')->where('documentary_id',$id)->delete();

        //删除关联点赞
        Db::name('documentary_likes')->where('documentary_id',$id)->delete();

        //删除关联评论
        Db::name('documentary_comment')->where('documentary_id',$id)->delete();

        return true;

    }

    //跟单详情
    public function detail($id){

        //基本信息
        $data = $this->where('documentary_id',$id)->find();

        $data['stage'] = Db::name('documentary_stage')->where('stage_id',$data['stage_id'])->value('stage');

        $data['ago'] = ceil((time() - strtotime($data['stage_time'])) / (3600 * 24));

        //关联客户
        $data['client'] = Db::name('client')->where('client_id',$data['client_id'])->field('client_id,client_name')->find();

        //关联联系人
        $data['staff'] = Db::name('crm_staff')->where('staff_id',$data['staff_id'])->field('staff_id,staff_name,head_img,phone')->find();

        $data['staff'] = !empty($data['staff']) ? $data['staff'] : [];

        //关联产品
        $goods = Db::name('documentary_goods_relevance')->alias('a')
        ->join('sh_goods b','a.goods_id = b.goods_id')
        ->join('sh_category c','b.cate_id = c.cate_id')
        ->field('b.goods_id,b.goods_name,b.specification1_name,b.specification2_name,b.specification2_name,b.specification1_value,b.specification2_value,b.specification3_value,c.cate_name')
        ->where('a.documentary_id',$id)->select();

        foreach($goods as &$v){
            $str = '';
            if(!empty($v['specification1_name'])){
                $str = $v['specification1_name'].':'.$v['specification1_value'];
            }
            if(!empty($v['specification2_name'])){
                $str .= ','.$v['specification2_name'].':'.$v['specification2_value'];
            }
            if(!empty($v['specification3_name'])){
                $str .= ','.$v['specification3_name'].':'.$v['specification3_value'];
            }

            if(!empty($str)){
                $str = "【 ".$str." 】"; 
            }

            $v['goods_name'] = $v['goods_name'] .= $str;

        }

        $data['goods'] = $goods;

        $data['images'] = !empty($data['images']) ? explode(',',$data['images']) : [];

        return $data;

    }

    //点赞  
    public function likes($id){

        $utid = \request()->header('userId');
        $staff = Db::name('crm_staff')->where('staff_id',$utid)->value('staff_name');

        $flag = Db::name('documentary_likes')->where('documentary_id',$id)->where('staff_id',$utid)->value('likes_id');

        if($flag){
            Db::name('documentary_likes')->where('likes_id',$flag)->delete();
        }else{
            $likes = [
                'documentary_id' => $id,
                'staff_id' => $utid,
                'staff_name' => $staff
            ];
            Db::name('documentary_likes')->insert($likes);
        }

        return true;

    }

    //评论
    public function comment($params){

        $utid = \request()->header('userId');
        $staff = Db::name('crm_staff')->where('staff_id',$utid)->value('staff_name');

        $params['create_at'] =date('Y-m-d H:i:s');
        $params['staff_id'] = $utid;
        $params['staff_name'] = $staff;

        Db::name('documentary_comment')->insert($params);

        return true;

    }

    //删除评论
    public function delComment($id){
        Db::name('documentary_comment')->where('parent_id',$id)->delete();
        Db::name('documentary_comment')->where('comment_id',$id)->delete();
        return true;
    }

    //跟单列表
    public function search($params){

        $page = !empty($params['page']) ? $params['page'] : 1;
        $pageSize = !empty($params['pageSize']) ? $params['pageSize'] : 10;

        $where = [];

        $client_where = [];

        $client_where['is_del'] = 0;

        if(!empty($params['title'])){
            $where['title'] = ['like','%'.$params['title'].'%'];
        }

        if(!empty($params['stage_id'])){
            $where['a.stage_id'] = $params['stage_id'];
        }

        if(!empty($params['create_staff'])){
            $where['a.create_staff'] = ['like','%'.$params['create_staff'].'%'];
        }  
        
        if(!empty($params['client_cate_id'])){
            $client_where['relevance.client_cate_id'] = $params['client_cate_id'];
        }

        if(!empty($params['region_id'])){
            $client_where['client.region_id'] = $params['region_id'];
        }

        if(!empty($params['create_at'])){
            $where['a.create_at'] = ['between',$params['create_at']];
        }

        if(!empty($client_where)){
            $client_ids = Db::name('client_category_relevance')->alias('relevance')
            ->join('sh_client client','relevance.client_id = client.client_id')
            ->where($client_where)->column('relevance.client_id');
            $where['a.client_id'] = ['in',$client_ids];
        }

        if(!empty($params['goods_id'])){
            $documentary_ids = Db::name('documentary_goods_relevance')->where('goods_id',$params['goods_id'])->column('documentary_id');
            $where['documentary_id'] = ['in',$documentary_ids];
        }

        if(!empty($params['overdue'])){
            $where['DATEDIFF(CURDATE(),a.stage_time)'] = ['exp','> c.days'];
        }

        $data = Db::name('client_documentary')->alias('a')
        ->join('sh_client b','a.client_id = b.client_id')
        ->join('sh_documentary_stage c','a.stage_id = c.stage_id')
        ->field('a.*,b.client_name')
        ->where($where)->page($page,$pageSize)->select();

        foreach($data as &$v){

            $v['stage'] = Db::name('documentary_stage')->where('stage_id',$v['stage_id'])->value('stage');

            if(!empty($v['staff_id'])){
                $v['staff_name'] = Db::name('crm_staff')->where('staff_id',$v['staff_id'])->value('staff_name');
            }

            $v['category'] = Db::name('client_category_relevance')->alias('a')
            ->join('sh_client_category b','a.client_cate_id = b.client_cate_id')
            ->where('a.client_id',$v['client_id'])
            ->value("GROUP_CONCAT(b.client_cate_name)");

            $v['goods'] = Db::name('documentary_goods_relevance')->alias('a')
            ->join('sh_goods b','a.goods_id = b.goods_id')
            ->where('a.documentary_id',$v['documentary_id'])
            ->value("GROUP_CONCAT(b.goods_name)");
        };

        $total = Db::name('client_documentary')->alias('a')
        ->join('sh_client b','a.client_id = b.client_id')
        ->field('a.documentary_id')
        ->where($where)->count();

        return [
            'data' => $data,
            'pager' => [
                'page' => $page,
                'pageSize' => $pageSize,
                'total' => $total
            ]
        ];

    }

    public function easyDocumentary($id){

        $data = Db::name('client_documentary')->alias('a')
        ->join('sh_client b','a.client_id = b.client_id')
        ->field('a.*,b.client_name')
        ->where('a.client_id',$id)
        ->select();

        foreach($data as &$v){

            $v['stage'] = Db::name('documentary_stage')->where('stage_id',$v['stage_id'])->value('stage');

            //点赞
            $v['likes'] = Db::name('documentary_likes')->field('staff_id,staff_name')->where('documentary_id',$v['documentary_id'])->select();
            //评论
            $v['comment'] = Db::name('documentary_comment')->where('documentary_id',$v['documentary_id'])->where('parent_id',0)->select();
            foreach($v['comment'] as &$c){
                $c['is_show'] = false;
                $c['child_comment'] = Db::name('documentary_comment')->where('parent_id',$c['comment_id'])->select();
                foreach($c['child_comment'] as &$cc){
                    $cc['is_show'] = false;
                }
            }
            //图片
            $v['images'] = !empty($v['images']) ? explode(',',$v['images']) : [];
        }

        return $data;

    }

    public function batchDel($documentary_ids){
        //删除主数据
        Db::name('client_documentary')->where('documentary_id','in',$documentary_ids)->delete();
        //删除点赞
        Db::name('documentary_likes')->where('documentary_id','in',$documentary_ids)->delete();
        //删除评论
        Db::name('documentary_comment')->where('documentary_id','in',$documentary_ids)->delete();
        //删除关联商品
        Db::name('documentary_goods_relevance')->where('documentary_id','in',$documentary_ids)->delete();
        return true;
    }

    public function delAll(){
        Db::execute('TRUNCATE table sh_client_documentary');
        Db::execute('TRUNCATE table sh_documentary_likes');
        Db::execute('TRUNCATE table sh_documentary_comment');
        Db::execute('TRUNCATE table sh_documentary_goods_relevance');
        return true;
    }

    public function stage(){
        return Db::name('documentary_stage')->field('stage_id,stage')->select();
    }

}